// ignore_for_file: invalid_use_of_protected_member
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_iconpicker/flutter_iconpicker.dart';
import 'package:animated_reorderable_list/animated_reorderable_list.dart';
import 'package:pass_log/app/core/utils/adapt.dart';
import 'package:pass_log/app/data/services/theme_service.dart';
import 'package:pass_log/app/data/providers/pass_provider.dart';

import 'type_controller.dart';
import 'widgets/type_item.dart';

typedef ObjItem = Map<String, dynamic>;

class TypePage extends GetView<TypeController> {
  const TypePage({super.key});

  static final plp = Get.find<PassListProvider>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("分类管理"),
        centerTitle: true,
      ),
      body: Obx(
        () => AnimatedReorderableListView(
          items: controller.typeList.value,
          itemBuilder: (BuildContext context, int index) {
            return TypeItem(
              key: ValueKey(controller.typeList.value[index]["id"]),
              item: controller.typeList.value[index],
              onEdit: (item) {
                if (item["id"] == "defaultType") return;
                TextEditingController nameCtr = TextEditingController();
                nameCtr.text = item["name"];
                controller.selectedIcon.value = {
                  "icon": item["icon"],
                  "fontFamily": item["fontFamily"],
                };
                Get.dialog(AlertDialog(
                  title: const Text("编辑分类"),
                  content: SizedBox(
                    width: Adapt.pt(300),
                    height: Adapt.pt(110),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        TextField(
                          controller: nameCtr,
                          autofocus: true,
                          decoration: const InputDecoration(
                            labelText: "分类名称",
                            hintText: "请输入分类名称",
                            prefixIcon: Icon(Icons.bookmark),
                            border: OutlineInputBorder(),
                          ),
                        ),
                        SizedBox(height: Adapt.pt(13)),
                        Flex(
                          direction: Axis.horizontal,
                          children: [
                            Container(
                              width: Adapt.pt(44),
                              height: Adapt.pt(44),
                              decoration: BoxDecoration(
                                border: Border.all(
                                  color: ThemeService.to.curColorScheme.primary,
                                  width: Adapt.pt(1.8),
                                ),
                                borderRadius: BorderRadius.circular(Adapt.pt(4)),
                              ),
                              child: Obx(
                                () => Icon(
                                  IconData(
                                    int.parse(controller.selectedIcon.value["icon"]!),
                                    fontFamily: controller.selectedIcon.value["fontFamily"],
                                  ),
                                  color: ThemeService.to.curColorScheme.onSurfaceVariant,
                                ),
                              ),
                            ),
                            SizedBox(width: Adapt.pt(10)),
                            Expanded(
                              child: SizedBox(
                                height: Adapt.pt(44),
                                child: ElevatedButton(
                                  style: TextButton.styleFrom(
                                    side: BorderSide(
                                      color: ThemeService.to.curColorScheme.primary,
                                      width: Adapt.pt(1.8),
                                    ),
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(Adapt.pt(4)),
                                    ),
                                  ),
                                  child: Text("点击选择图标", style: TextStyle(fontSize: Adapt.pt(14))),
                                  onPressed: () => _pickIcon(context, controller),
                                ),
                              ),
                            )
                          ],
                        )
                      ],
                    ),
                  ),
                  actions: [
                    TextButton(
                      onPressed: () {
                        Get.back();
                        nameCtr.clear();
                        controller.selectedIcon.value = {"icon": "60556", "fontFamily": "MaterialIcons"};
                      },
                      child: Text("取消", style: TextStyle(fontSize: Adapt.pt(16))),
                    ),
                    TextButton(
                      onPressed: () => controller.editType(nameCtr.text, item),
                      child: Text("保存", style: TextStyle(fontSize: Adapt.pt(16))),
                    )
                  ],
                ));
              },
              onDelete: (item) {
                if (item["id"] == "defaultType") return;
                Get.dialog(AlertDialog(
                  title: const Text("系统提示"),
                  content: SizedBox(
                    width: Adapt.pt(300),
                    child: Text(
                      "确定要删除分类【${item["name"]}】吗？",
                      style: TextStyle(fontSize: Adapt.pt(16)),
                    ),
                  ),
                  actions: [
                    TextButton(
                      onPressed: () => Get.back(),
                      child: Text("取消", style: TextStyle(fontSize: Adapt.pt(16))),
                    ),
                    TextButton(
                      onPressed: () {
                        // 先把要删除的分类下的密码全部移至默认分类
                        for (var i = 0; i < plp.list.length; i++) {
                          if (plp.list[i] != null && plp.list[i]?["type_id"] == item["id"]) {
                            plp.changePassType(plp.list[i]!, "defaultType");
                          }
                        }
                        plp.refreshPass();
                        // 然后才能删除分类
                        controller.deleteType(item);
                        Get.back();
                      },
                      child: Text("确定", style: TextStyle(fontSize: Adapt.pt(16))),
                    )
                  ],
                ));
              },
            );
          },
          // 拖动时代理列表项的绘制效果
          proxyDecorator: (child, index, animation) {
            return Material(
              elevation: 0.1,
              color: Colors.transparent,
              shadowColor: Colors.black.withOpacity(0.5),
              child: Opacity(
                opacity: 0.8,
                child: child,
              ),
            );
          },
          enterTransition: [FlipInX(), ScaleIn()],
          exitTransition: [SlideInLeft()],
          insertDuration: const Duration(milliseconds: 300),
          removeDuration: const Duration(milliseconds: 300),
          onReorder: controller.reorderType,
          isSameItem: (a, b) => a["id"] == b["id"],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        heroTag: "addType",
        onPressed: () {
          TextEditingController nameCtr = TextEditingController();
          Get.dialog(AlertDialog(
            title: const Text("添加分类"),
            content: SizedBox(
              width: Adapt.pt(300),
              height: Adapt.pt(110),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  TextField(
                    controller: nameCtr,
                    autofocus: true,
                    decoration: const InputDecoration(
                      labelText: "分类名称",
                      hintText: "请输入分类名称",
                      prefixIcon: Icon(Icons.bookmark),
                      border: OutlineInputBorder(),
                    ),
                  ),
                  SizedBox(height: Adapt.pt(13)),
                  Flex(
                    direction: Axis.horizontal,
                    children: [
                      Container(
                        width: Adapt.pt(44),
                        height: Adapt.pt(44),
                        decoration: BoxDecoration(
                          border: Border.all(
                            color: ThemeService.to.curColorScheme.primary,
                            width: Adapt.pt(1.8),
                          ),
                          borderRadius: BorderRadius.circular(Adapt.pt(4)),
                        ),
                        child: Obx(
                          () => Icon(
                            IconData(
                              int.parse(controller.selectedIcon.value["icon"]!),
                              fontFamily: controller.selectedIcon.value["fontFamily"],
                            ),
                            color: ThemeService.to.curColorScheme.onSurfaceVariant,
                          ),
                        ),
                      ),
                      SizedBox(width: Adapt.pt(10)),
                      Expanded(
                        child: SizedBox(
                          height: Adapt.pt(44),
                          child: ElevatedButton(
                            style: TextButton.styleFrom(
                              side: BorderSide(
                                color: ThemeService.to.curColorScheme.primary,
                                width: Adapt.pt(1.8),
                              ),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(Adapt.pt(4)),
                              ),
                            ),
                            child: Text("点击选择图标", style: TextStyle(fontSize: Adapt.pt(14))),
                            onPressed: () => _pickIcon(context, controller),
                          ),
                        ),
                      )
                    ],
                  )
                ],
              ),
            ),
            actions: [
              // TextButton(
              //   onPressed: () => controller.resetType(),
              //   child: Text("重置分类", style: TextStyle(fontSize: Adapt.pt(16))),
              // ),
              TextButton(
                child: Text("取消", style: TextStyle(fontSize: Adapt.pt(16))),
                onPressed: () {
                  Get.back();
                  nameCtr.clear();
                  controller.selectedIcon.value = {"icon": "60556", "fontFamily": "MaterialIcons"};
                },
              ),
              TextButton(
                child: Text("保存", style: TextStyle(fontSize: Adapt.pt(16))),
                onPressed: () => controller.createType(nameCtr.text),
              )
            ],
          ));
        },
        child: const Icon(Icons.add),
      ),
    );
  }

  // flutter_iconpicker 图标选择器
  _pickIcon(BuildContext context, TypeController ctr) async {
    IconData? iconData = await showIconPicker(
      context,
      iconPackModes: [IconPack.roundedMaterial],
      barrierDismissible: false,
      title: const Text("选择图标"),
      searchHintText: "搜索图标",
      closeChild: Text("返回", style: TextStyle(fontSize: Adapt.pt(16))),
    );
    if (iconData != null) {
      ctr.selectedIcon.value = {
        "icon": iconData.codePoint.toString(),
        "fontFamily": iconData.fontFamily!,
      };
    }
  }
}
